package com.dtanner.books;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.swing.text.html.HTML.Tag;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.xhtmlrenderer.pdf.ITextRenderer;

public class GetBooks {

	private final static Logger logger = Logger.getLogger(GetBooks.class);

	private final static String baseUrl = "http://maxwellinstitute.byu.edu/publications/books/";
	private NameValuePair query;
	private HttpLib http;

	private Map<String, String> book;
	private String bookName;

	public GetBooks() {
		http = new HttpLib();
		book = new LinkedHashMap<String, String>();
	}

	public String getBookByNumber(Integer bookNumber) {
		query = new NameValuePair("bookId", bookNumber.toString());
		return http.getRequest(baseUrl, query);
	}

	public void processWebSite(int bookID) {
		book = new LinkedHashMap<String, String>();
		try {
			Document doc = Jsoup.connect(baseUrl + "?bookid=" + bookID).get();
			Elements name = doc.getElementsByClass("menu_item");

			bookName = doc.getElementById("bread_crumbs")
					.getElementsByTag("strong").get(0).text();
			String[] chapterNumbers = new String[name.size()];
			String[] chapterNames = new String[name.size()];
			for (int i = 0; i < chapterNumbers.length; i++) {
				if (i == 0) {
					continue;
				}
				Element next = name.get(i);
				Elements links = next.getElementsByTag("a");
				Element link = links.get(0);
				String chapterName = link.text();
				chapterNames[i] = chapterName;
				try {
					Attributes attr = link.attributes();
					String href1 = attr.get("href");
					String[] href = href1.split("&");
					chapterNumbers[i] = href[href.length - 1]
							.replace("id=", "");
				} catch (NullPointerException e) {
					logger.info(StackToString.toString(e));
				}
			}
			for (int i = 1; i < chapterNames.length; i++) {
				getChapter(chapterNames[i], bookID, chapterNumbers[i]);
				break;
			}
			// writeBookToTXT();

		} catch (IOException e) {
			logger.info(StackToString.toString(e));
		} catch (NullPointerException e) {
			logger.info(StackToString.toString(e));
		}
	}

	public void getChapter(String chapterName, Integer bookID, String chapterID) {
		try {
			System.out.println(chapterName);
//			HTTPCommands http = new HTTPCommands();
//			String query = http.constructQuery("bookid", bookID + "", "chapid", chapterID + "");
//			GetMethod get = new GetMethod(baseUrl);
//			get.setQueryString(query);
//			logger.info(http.httpRequest(get));
//			
//			HTML2PDF to_pdf = new HTML2PDF();
//			
//			to_pdf.convertToXML(new BufferedInputStream(new ByteArrayInputStream(http.response.getBytes())));
//			
//			OutputStream pdf = new FileOutputStream(new File("Book " + bookID + " Chapter " + chapterID + ".pdf"));
//			pdf.write(HTML2PDF.fo2PDF(to_pdf.getDoc()));
//		} catch (HttpException e) {
//			logger.info(StackToString.toString(e));
//		} catch (IOException e) {
//			logger.info(StackToString.toString(e));
//		}
			Document doc;
			 try {
				 doc = Jsoup.connect(baseUrl + "?bookid=" + bookID + "&chapid=" +  chapterID)
						 .get();
			 } catch (Exception e) {
				 doc = Jsoup.connect(baseUrl + "?bookid=" + bookID + "&chapid=" + chapterID)
						 .get();
			 }
			 
			 Element body = doc.getElementsByTag("body").get(0);
			 body.attributes().put("style", body.attributes().get("style").replace("-webkit", "webkit"));
			 Element script = doc.getElementsByTag("script").get(1);
			 script.attributes().put("type","text/javascript");
			 
			 Elements links = doc.getElementsByTag("link");
			 for (Element link: links){
				 if (!link.parent().tag().equals(Tag.HEAD)){
					 link.remove();
				 }
			 }
			 
			 Elements ps = doc.getElementsByTag("p");
			 for (Element p : ps){
				 if (p.text().equals("")){
					 p.append("<br />");
				 }
			 }
			 
			 HTML2PDF to_pdf = new HTML2PDF();
			 String html = doc.outerHtml();
			 ITextRenderer renderer = new ITextRenderer();
			 renderer.setDocument(to_pdf.convertToXML(new BufferedInputStream(new ByteArrayInputStream(html.getBytes()))), "");
				
			 OutputStream pdf = new FileOutputStream(new File("Book " + bookID + " Chapter " + chapterID + ".pdf"));
			 pdf.write(HTML2PDF.fo2PDF(to_pdf.getDoc()));
				
		
		 } catch (FileNotFoundException e) {
			 logger.info(StackToString.toString(e));
		 } catch (IOException e) {
			 logger.info(StackToString.toString(e));
		 }
	}

	private void writeBookToTXT() {
		StringWriter writer = new StringWriter();
		for (String contents : book.values()) {
			writer.write(contents);
			writer.write("\n\n");
		}

		String fileName = bookName.replace(":", " -") + ".txt";
		System.out.println(fileName);
		try {
			FileWriter fw = new FileWriter(fileName, true);
			fw.write(writer.toString());
			fw.flush();
			fw.close();
		} catch (IOException e) {
			logger.info(StackToString.toString(e));
		}
	}

	public static void main(String[] args) {
		GetBooks books = new GetBooks();
		// String str = books.getBookByNumber(2);
		// int[] booksList = { 117, 118, 119, 103 };
		// for (int book : booksList) {
		// books.processWebSite(book);
		// }
		books.processWebSite(117);

	}

}